<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="24">
          <a-form-item label="姓名" v-bind="validateInfos.name">
            <a-input v-model:value="formData.name" placeholder="请输入姓名" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="电话" v-bind="validateInfos.phone">
            <a-input v-model:value="formData.phone" placeholder="请输入电话" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="邮箱" v-bind="validateInfos.email">
            <a-input v-model:value="formData.email" placeholder="请输入邮箱" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="身份证" v-bind="validateInfos.idnumber">
            <a-input v-model:value="formData.idnumber" placeholder="请输入身份证" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="身份证正面" v-bind="validateInfos.picture1">
            <j-image-upload
              :fileMax="1"
              :action="idCardUploadApi"
              :extraData="(file)=>buildIdCardUploadData(file,'idcard_front.jpg')"
              v-model:value="formData.picture1"
              :disabled="disabled"
              @uploadSuccess="(payload)=>handleIdCardUpload('picture1', payload)"
            ></j-image-upload>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="身份证反面" v-bind="validateInfos.picture2">
            <j-image-upload
              :fileMax="1"
              :action="idCardUploadApi"
              :extraData="(file)=>buildIdCardUploadData(file,'idcard_back.jpg')"
              v-model:value="formData.picture2"
              :disabled="disabled"
              @uploadSuccess="(payload)=>handleIdCardUpload('picture2', payload)"
            ></j-image-upload>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="营业执照1" v-bind="validateInfos.license1">
            <j-image-upload
              :fileMax="1"
              :action="idCardUploadApi"
              :extraData="(file)=>buildIdCardUploadData(file,'license1.jpg')"
              v-model:value="formData.license1"
              :disabled="disabled"
              @uploadSuccess="(payload)=>handleLicenseUpload('license1', payload)"
            ></j-image-upload>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="营业执照2" v-bind="validateInfos.license2">
            <j-image-upload
              :fileMax="1"
              :action="idCardUploadApi"
              :extraData="(file)=>buildIdCardUploadData(file,'license2.jpg')"
              v-model:value="formData.license2"
              :disabled="disabled"
              @uploadSuccess="(payload)=>handleLicenseUpload('license2', payload)"
            ></j-image-upload>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="授权书" v-bind="validateInfos.authorization1">
            <j-image-upload
              :fileMax="1"
              :action="idCardUploadApi"
              :extraData="(file)=>buildIdCardUploadData(file,'authorization1.jpg')"
              v-model:value="formData.authorization1"
              :disabled="disabled"
              @uploadSuccess="(payload)=>handleAuthorizationUpload(payload)"
            ></j-image-upload>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="地址" v-bind="validateInfos.address">
            <a-input v-model:value="formData.address" placeholder="请输入地址" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="合同编号" v-bind="validateInfos.contractcode">
            <a-input v-model:value="formData.contractcode" placeholder="请输入合同编号" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="合作有效期" v-bind="validateInfos.duration">
            <a-input v-model:value="formData.duration" placeholder="请输入合作有效期（年）" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="合同模板" v-bind="validateInfos.templateid">
	          <j-dict-select-tag v-model:value="formData.templateid" dictCode="esign_contracts,templatename,templateid" placeholder="请选择合同模板" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="合同ID" v-bind="validateInfos.flowId">
            <a-input v-model:value="formData.flowId" placeholder="请输入合同ID" disabled></a-input>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted, toRaw } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../EsignSign.api';
  import { Form } from 'ant-design-vue';
  
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: ()=>{} },
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const idCardUploadApi = '/tencent_esign/upload/uploadFile';
  const buildIdCardUploadData = (file: any, fallbackName = 'upload.jpg') => {
    const name = file?.name || fallbackName;
    const extFromName = name?.includes('.') ? name.split('.').pop() : '';
    const mime = file?.type || '';
    const extFromMime = mime.includes('/') ? mime.split('/').pop() : '';
    const ext = (extFromName || extFromMime || 'jpg').toUpperCase();
    return {
      fileType: ext,
      fileName: name,
    };
  };

  async function handleIdCardUpload(field: 'picture1' | 'picture2', payload: any) {
    const fileId = payload?.response?.result?.fileId;
    if (!fileId) {
      createMessage.warning('上传成功但未返回 fileId，无法同步身份证信息');
      return;
    }
    if (field === 'picture1') {
      formData.idcardpic1 = fileId;
    } else {
      formData.idcardpic2 = fileId;
    }
    
    // 同时调用本框架的上传接口，保存图片到服务器
    const originFile = payload?.file?.originFileObj;
    if (originFile) {
      try {
        const uploadResponse = await defHttp.uploadFile(
          {
            url: '/sys/common/upload',
          },
          {
            file: originFile,
            data: {
              biz: 'esign_sign',
            },
          },
          {
            isReturnResponse: true,
          }
        );
        
        // 将返回的图片地址保存到对应字段
        if (uploadResponse && uploadResponse.message) {
          if (field === 'picture1') {
            formData.picture1 = uploadResponse.message;
          } else {
            formData.picture2 = uploadResponse.message;
          }
        }
      } catch (error) {
        console.error('上传图片到服务器失败:', error);
        // 不阻止流程，只记录错误
      }
    }
    
    if (!formData.id) {
      return;
    }
    try {
      const params: Record<string, any> = {
        id: formData.id,
      };
      if (field === 'picture1') {
        params.idcardpic1 = fileId;
        if (formData.picture1) {
          params.picture1 = formData.picture1;
        }
      } else {
        params.idcardpic2 = fileId;
        if (formData.picture2) {
          params.picture2 = formData.picture2;
        }
      }
      await saveOrUpdate(params, true);
      createMessage.success('身份证文件已同步保存');
    } catch (error) {
      console.error('同步身份证fileId失败:', error);
      createMessage.error('同步身份证信息失败，请稍后重试');
    }
  }

  async function handleLicenseUpload(field: 'license1' | 'license2', payload: any) {
    const fileId = payload?.response?.result?.fileId;
    if (!fileId) {
      createMessage.warning('上传成功但未返回 fileId，无法同步营业执照信息');
      return;
    }
    if (field === 'license1') {
      formData.licensepic1 = fileId;
    } else {
      formData.licensepic2 = fileId;
    }
    
    // 同时调用本框架的上传接口，保存图片到服务器
    const originFile = payload?.file?.originFileObj;
    if (originFile) {
      try {
        const uploadResponse = await defHttp.uploadFile(
          {
            url: '/sys/common/upload',
          },
          {
            file: originFile,
            data: {
              biz: 'esign_sign',
            },
          },
          {
            isReturnResponse: true,
          }
        );
        
        // 将返回的图片地址保存到对应字段
        if (uploadResponse && uploadResponse.message) {
          if (field === 'license1') {
            formData.license1 = uploadResponse.message;
          } else {
            formData.license2 = uploadResponse.message;
          }
        }
      } catch (error) {
        console.error('上传图片到服务器失败:', error);
        // 不阻止流程，只记录错误
      }
    }
    
    if (!formData.id) {
      return;
    }
    try {
      const params: Record<string, any> = {
        id: formData.id,
      };
      if (field === 'license1') {
        params.licensepic1 = fileId;
        if (formData.license1) {
          params.license1 = formData.license1;
        }
      } else {
        params.licensepic2 = fileId;
        if (formData.license2) {
          params.license2 = formData.license2;
        }
      }
      await saveOrUpdate(params, true);
      createMessage.success('营业执照文件已同步保存');
    } catch (error) {
      console.error('同步营业执照fileId失败:', error);
      createMessage.error('同步营业执照信息失败，请稍后重试');
    }
  }

  async function handleAuthorizationUpload(payload: any) {
    const fileId = payload?.response?.result?.fileId;
    if (!fileId) {
      createMessage.warning('上传成功但未返回 fileId，无法同步授权书信息');
      return;
    }
    formData.authorizationpic = fileId;
    
    // 同时调用本框架的上传接口，保存图片到服务器
    const originFile = payload?.file?.originFileObj;
    if (originFile) {
      try {
        const uploadResponse = await defHttp.uploadFile(
          {
            url: '/sys/common/upload',
          },
          {
            file: originFile,
            data: {
              biz: 'esign_sign',
            },
          },
          {
            isReturnResponse: true,
          }
        );
        
        // 将返回的图片地址保存到对应字段
        if (uploadResponse && uploadResponse.message) {
          formData.authorization1 = uploadResponse.message;
        }
      } catch (error) {
        console.error('上传图片到服务器失败:', error);
        // 不阻止流程，只记录错误
      }
    }
    
    if (!formData.id) {
      return;
    }
    try {
      const params: Record<string, any> = {
        id: formData.id,
        authorizationpic: fileId,
      };
      if (formData.authorization1) {
        params.authorization1 = formData.authorization1;
      }
      await saveOrUpdate(params, true);
      createMessage.success('授权书文件已同步保存');
    } catch (error) {
      console.error('同步授权书fileId失败:', error);
      createMessage.error('同步授权书信息失败，请稍后重试');
    }
  }

  const formData = reactive<Record<string, any>>({
    id: '',
    name: '',   
    phone: '',   
    email: '',   
    idnumber: '',   
    picture1: '',
    picture2: '',
    idcardpic1: '',
    idcardpic2: '',
    license1: '',
    license2: '',
    licensepic1: '',
    licensepic2: '',
    authorization1: '',
    authorizationpic: '',
    contractcode: '',
    duration: '',
    templateid: '',   
    flowId: '',   
    address: '',   
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  
  /**
   * 新增
   */
  function add() {
    edit({ duration: '10' });
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      // 如果 duration 为空，则设置默认值为 10
      if (!tmpData.duration) {
        tmpData.duration = '10';
      }
      //赋值
      Object.assign(formData, tmpData);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    const model = { ...toRaw(formData) };
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    height: 500px !important;
    overflow-y: auto;
    padding: 14px;
  }
</style>
